package com.etv.launcher.common.utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * 文件处理工具类
 */
public class FileUtil {

    //对象写入对象
    public static boolean writeObject(String path, Object target) {
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(new File(path));
            ObjectOutputStream objectOutput = new ObjectOutputStream(outputStream);
            objectOutput.writeObject(target);
        } catch (Exception e) {
            try {
                if (outputStream != null)
                    outputStream.close();
            } catch (Exception e1) {
                e1.printStackTrace();
                return false;
            }
        }
        return true;
    }

    //对象读取
    public static Object readObject(String path) {
        Object object = null;
        FileInputStream inputStream = null;

        try {
            inputStream = new FileInputStream(new File(path));
            ObjectInputStream objectInput = new ObjectInputStream(inputStream);
            object = objectInput.readObject();
        } catch (Exception e) {
            try {
                if (inputStream != null)
                    inputStream.close();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }

        return object;
    }

    //文件/目录是否存在
    public static boolean isExits(String path) {
        File file = new File(path);
        return file.exists();
    }

    public static boolean isEmpty(String path) {
        File file = new File(path);

        if (file.isFile())
            return file.length()<=0?true:false;
        else if (file.isDirectory())
            return file.listFiles().length<0?true:false;

        return false;
    }

    //创建文件
    public static boolean createFile(String path) {
        try {
            File file = new File(path);
            createDirectory(path.substring(0,path.lastIndexOf("/")));
            file.createNewFile();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    //创建文件夹
    public static boolean createDirectory(String path) {
        try {
            File file = new File(path);
            file.mkdirs();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    /**
     * 导出文件
     * @param fileName
     * @param data
     * @return
     */
    public static boolean exportFile(String fileName,String data){
        try {
            // 获取下载目录的路径
            File downloadDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

            //创建文件
            File jsonFile = new File(downloadDir, fileName+".json");
            if (!jsonFile.exists())
                jsonFile.createNewFile();

            // 写入内容到文件
            FileWriter writer = new FileWriter(jsonFile);
            writer.write(data);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    /**
     * 从uri中读取内存对象列表
     *
     * @param uri
     * @param context
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> List<T> getListFromUri(Uri uri, Context context, Class<T> clazz){

        try {
            InputStream inputStream = context.getContentResolver().openInputStream(uri);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }


            return JSONObject.parseArray(stringBuilder.toString(),clazz);
        } catch (Exception e) {
            ToastUtil.show(context,"文件被损坏，无法导入！");
            return null;
        }
    }

    /**
     * 从uri中获取对象
     * @param uri
     * @param context
     * @param clazz
     * @return
     * @param <T>
     */
    public static <T> T getObjectFromUri(Uri uri, Context context,Class<T> clazz){

        try {
            InputStream inputStream = context.getContentResolver().openInputStream(uri);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }

            // 使用Gson将JSON字符串转换为对象
            return JSONObject.parseObject(stringBuilder.toString(),clazz);

        } catch (Exception e) {
            ToastUtil.show(context,"文件被损坏，无法导入！");
            return null;
        }
    }

    //读入更新日志
    public static String readAssetFile(AssetManager assetManager, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();

        try {
            InputStream inputStream = assetManager.open(fileName);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }

            bufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return stringBuilder.toString();
    }

    public static void drawableToFile(Drawable drawable, String filePath) {
        // 确保Drawable不为空
        if (drawable == null) {
            Log.e("DrawableToFile", "Drawable is null");
            return;
        }
        Bitmap bitmap;
        // 优化：如果 Drawable 本身是 BitmapDrawable，直接获取 Bitmap
        if (drawable instanceof BitmapDrawable) {
            bitmap = ((BitmapDrawable) drawable).getBitmap();
        } else {
            bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
            drawable.draw(canvas);
        }
        File file = new File(filePath);
        try (OutputStream outputStream = new FileOutputStream(file)) {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // **核心优化点2：高效的Bitmap存储**
    public static void saveBitmap(Bitmap bitmap, String filePath) {
        File dir = new File(filePath);

        try (OutputStream os = new BufferedOutputStream(new FileOutputStream(dir))) { // **缓冲流优化**
            bitmap.compress(Bitmap.CompressFormat.PNG, 85, os); // 质量优化
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
//            bitmap.recycle(); // **及时回收Bitmap**
        }
    }

    public static Bitmap drawableToBitmap (@NonNull Drawable drawable){
        Bitmap bitmap;
        // 优化：如果 Drawable 本身是 BitmapDrawable，直接获取 Bitmap
        if (drawable instanceof BitmapDrawable) {
            bitmap = ((BitmapDrawable) drawable).getBitmap();
        } else {
            bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
            drawable.draw(canvas);
        }

        return bitmap;
    }

}
